//图片路径拼接
function formatAvater(avater, imgPath) {
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return imgPath + avater;
  }
}
//图片路径拼接(商品头图)
function formatAvaterByProHead(avater) {
  const app = getApp();
  if (avater != null && avater.indexOf("http") == 0) {
    return avater;
  } else {
    return 'https://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/product/show/source/' + avater;
  }
}
// 计算海报文字显示的行数
function textByteLength(text, num) { // text为传入的文本  num为单行显示的字节长度
  let strLength = 0; // text byte length
  let rows = 1;
  let str = 0;
  let arr = [];
  for (let j = 0; j < text.length; j++) {
    if (text.charCodeAt(j) > 255) {
      strLength += 2;
      if (strLength > rows * num) {
        strLength++;
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    } else {
      strLength++;
      if (strLength > rows * num) {
        arr.push(text.slice(str, j));
        str = j;
        rows++;
      }
    }
  }
  arr.push(text.slice(str, text.length));
  return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
}

// 圆形图片
function circleImg(ctx, img, x, y, r) {
  ctx.save();
  ctx.beginPath();
  var d = 2 * r;
  var cx = x + r;
  var cy = y + r;
  ctx.arc(cx, cy, r, 0, 2 * Math.PI, false);
  ctx.clip();
  ctx.drawImage(img, x, y, d, d);
  ctx.restore();
}

function fillRoundRect(cxt, x, y, width, height, radius, fillColor) {
  //圆的直径必然要小于矩形的宽高          
  if (2 * radius > width || 2 * radius > height) {
    return false;
  }
  cxt.save();
  cxt.translate(x, y);
  //绘制圆角矩形的各个边  
  drawRoundRectPath(cxt, width, height, radius);
  cxt.fillStyle = fillColor || "#000"; //若是给定了值就用给定的值否则给予默认值  
  cxt.fill();
}

function drawRoundRectPath(cxt, width, height, radius) {
  cxt.beginPath();
  //从右下角顺时针绘制，弧度从0到1/2PI  
  cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);

  //矩形下边线  
  cxt.lineTo(radius, height);

  //左下角圆弧，弧度从1/2PI到PI  
  cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);

  //矩形左边线  
  cxt.lineTo(0, radius);

  //左上角圆弧，弧度从PI到3/2PI  
  cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);

  //上边线  
  cxt.lineTo(width - radius, 0);

  //右上角圆弧  
  cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);

  //右边线  
  cxt.lineTo(width, height - radius);
  cxt.closePath();
}

module.exports = {
  formatAvater: formatAvater,
  formatAvaterByProHead: formatAvaterByProHead,
  textByteLength: textByteLength,
  circleImg: circleImg,
  fillRoundRect: fillRoundRect
}